﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics.Eventing.Reader;

namespace EventLogEntryReader
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("EventLogEntryReader started");

            // creating thread

            ThreadStart sentryThreadStart = new ThreadStart(LaunchSentry);
            Thread sentryThread = new Thread(sentryThreadStart);
            sentryThread.Start();

            Console.ReadLine();
            sentryThread.Abort();
            Console.WriteLine("EventLogEntryReader stopped");

            Console.ReadLine();

        }

        private static void LaunchSentry()
        {
            EventLogWatcher watcher = null;

            try
            {
                Console.WriteLine("Sentry Thread Started");

                EventLogQuery subscriptionQuery = new EventLogQuery("Application", PathType.LogName, "*[System/*]");
                watcher = new EventLogWatcher(subscriptionQuery);
                watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);
                watcher.Enabled = true;
                for (;;)
                {
                    // Wait for events to occur. 
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine("Sentry Thread Aborted");
            }
            finally
            {
                watcher.Enabled = false;
                if (watcher != null)
                {
                    watcher.Dispose();
                }
            }
        }


        public static void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
        {
            if (arg.EventRecord != null)
            {
                Console.WriteLine("Received event from " + arg.EventRecord.ProviderName + ".");
                Console.WriteLine("Description: " + arg.EventRecord.Properties[0].Value);
            }
            else
            {
                Console.WriteLine("The event instance was null.");
            }
        }

    }
}
